"use strict";
const mockUtil = require("mockjs");
const fs = require("fs");
const path = require("path");

function mockData(ruleFile) {
    /**
     * 处理生成PLSQL语句。
     * 结果默认保存在datas目录下，结果名为 ruleFilename.sql
     */
    let filename = path.win32.basename(ruleFile);
    fs.exists(ruleFile, (exists) => {
        if (exists) {
            fs.readFile(ruleFile, 'utf8', (err, rule) => {
                if (err) throw err;
                let obj = eval("(" + rule + ")");
                let results=generateMockDatas(100,filename,obj);
                fs.writeFile("datas/" + filename + ".sql", results.join("\n"), "utf8", function(err) {
                    if (err) {
                        console.log(err);
                    } 
                });
            });
        } else {
            console.log("could't found the file:" + ruleFile);
        }
    });
}

function mockDatas(ruleDirectory) {
    /**
     * 遍历文件夹下的所有文件，逐一处理生成PLSQL语句。
     * 结果默认保存在datas目录下，结果名为 ruleFilename.sql
     */
    fs.exists(ruleDirectory,(exists)=>{
        if(exists){
            fs.readdir(ruleDirectory,function(err,files){
                files.forEach(function(file) {
                    mockData(ruleDirectory+"/"+file);
                }, this);
            });
        }else{
            console.log("the directory "+ruleDirectory+ " is not exists");
        }
    });
}

function printMockData(ruleFile) {
    /**
     * 处理生成PLSQL语句，结果输出到控制台。
     */
    let filename = path.win32.basename(ruleFile);
    fs.exists(ruleFile, (exists) => {
        if (exists) {
            fs.readFile(ruleFile, 'utf8', (err, rule) => {
                if (err) throw err;
                let obj = eval("(" + rule + ")");
                let results=generateMockDatas(5,filename,obj);
                console.log(results);
            });
        } else {
            console.log("could't found the file:" + ruleFile);
        }
    });
}

function generateMockDatas(count, tableName, template) {
    let result=[];
    //处理规则
    let Random = mockUtil.Random;
    Random.guid();
    Random.ctitle();
    let i = 0;
    while (i < count) {
        let mockResult = mockUtil.mock(template);
        let sql = ["insert into "];
        sql.push(tableName);
        let fields = [];
        let values = [];
        for (let e in mockResult) {
            fields.push(e);
            if (mockResult[e].constructor == Number) {
                values.push(mockResult[e]);
            } else {
                values.push("'" + mockResult[e] + "'");
            }
        }
        sql.push("(");
        sql.push(fields.join(','));
        sql.push(") values(");
        sql.push(values.join(','));
        sql.push(");");
        result.push(sql.join(''));
        i++;
    }
    return result;
}
exports.printMockData = printMockData;
exports.mockData = mockData;
exports.mockDatas = mockDatas;